package cc.rengu.redp.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.lionsoul.ip2region.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;

@Slf4j
public class AddressUtil {

    private static DbSearcher dbSearcher = null;

    private static void initDbSearcher()  {
        try {
            String dbPath = AddressUtil.class.getResource("/ip2region/ip2region.db").getPath();
            File file = new File(dbPath);
            if (!file.exists()) {
                String tmpDir = System.getProperties().getProperty("java.io.tmpdir");
                file = new File(tmpDir, "ip.db");
                FileUtils.copyInputStreamToFile(Objects.requireNonNull(AddressUtil.class.getClassLoader().getResourceAsStream("classpath:ip2region/ip2region.db")), file);
            }
            byte[] bytes = IOUtils.toByteArray(new FileInputStream(file));
            dbSearcher = new DbSearcher(new DbConfig(), bytes);
        } catch (IOException | DbMakerConfigException e) {
            log.error("复制文件IO异常", e);
        }
    }

    public static String getCityInfo(String ip) {
        if (!Util.isIpAddress(ip)) {
            log.error("Error: Invalid ip address: {}", ip);
            return "";
        }

        if (dbSearcher == null) {
            initDbSearcher();
        }

        if (dbSearcher == null) {
            return "";
        }

        try {
            DataBlock dataBlock = dbSearcher.memorySearch(ip);
            return dataBlock.getRegion();
        } catch (IOException e) {
            log.error("读取文件IO异常", e);
        }

        return "";

    }

}